package com.example.bookstore.controllers;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.example.bookstore.details.CustomerDetails;
import com.example.bookstore.entity.Customer;
import com.example.bookstore.exception.CustomerNotFoundException;
import com.example.bookstore.exception.InvalidParameterException;

@ManagedBean(name="custCtrl")
@SessionScoped
public class CustomerController {
	@PersistenceContext(name = "dukesbooks")
	private EntityManager em;

	public Long createCustomer(CustomerDetails details) {
		return 0L;
	}

	public CustomerDetails getDetails(Long customerId)
			throws CustomerNotFoundException, InvalidParameterException {
		// returns the CustomerDetails for the specified customer
		System.err.println("CustomerControllerBean getDetails");

		CustomerDetails result = null;

		if (customerId == null) {
			throw new InvalidParameterException("null customerId");
		}

		try {
			Customer customer = em.find(Customer.class, customerId);

			if (customer == null) {
				throw new CustomerNotFoundException(customerId);
			} else {
				result = new CustomerDetails();
				result.setCity(customer.getCity());
				result.setFirstName(customer.getFirstName());
				result.setLastName(customer.getLastName());
				result.setEmail(customer.getEmailAddress());
				result.setPhone(customer.getPhoneNumber());
				result.setStreet(customer.getStreet());
				result.setState(customer.getState());
			}
		} catch (Exception ex) {
			System.err
					.println("CustomerControllerBean.getDetails: Caught an exception.");
			ex.printStackTrace();
		}

		return result;
	}

	public CustomerDetails getCustomer(long customerId) {
		// TODO Auto-generated method stub
		return null;
	}
}
